<?php

namespace App\Admin\Actions\Chapter;

use App\Jobs\AutoRemovePosterZip;
use App\Models\Chapter;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\RowAction;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use PhpZip\Exception\ZipEntryNotFoundException;
use PhpZip\Exception\ZipException;
use PhpZip\ZipFile;

class DownloadPoster extends RowAction
{
    protected string $title = '海报下载';

    /**
     * @throws ZipEntryNotFoundException
     * @throws ZipException
     */
    public function handle(Request $request): Response
    {
        $application = $request->application;
        $storage = $application->domainPool->storage();

        $chapter = Chapter::ofAdmin()->find($this->getKey());
        $zipFile = new ZipFile();
        foreach ($chapter->players as $player) {
            $poster = $player->posters()->latest()->first();
            $extension = pathinfo($poster->cover, PATHINFO_EXTENSION);
            $stream = $storage->get($poster->cover);
            $zipFile->addFromString(sprintf('%s.%s', $player->name, $extension), $stream);
        }

        $password = $request->application->password;
        if ($password) {
            $zipFile->setPassword($password);
        }

        $file = sprintf(
            'zips/%s-%s.zip',
            $chapter->season->title,
            $chapter->title
        );
        $storage->put($file, $zipFile->outputAsString());
        $zipFile->close();

        AutoRemovePosterZip::dispatch($storage, $file)->delay(now()->addMinutes(30));

        return $this->response()
            ->download($storage->url($file))
            ->success('成功下载海报图片: '.count($chapter->players));
    }

    public function confirm(): array
    {
        $chapter = Chapter::find($this->getKey());

        $posterNum = $chapter->players()->whereHas('posters', function (Builder $query) {
            $query->whereNotNull('cover');
        })->count();
        $itemNum = $chapter->players()->count();

        return [
            '海报生成进度'.$posterNum.'/'.$itemNum.'确认要下载么',
            '如果刚刚点击更新,请稍后再下载,观察选手海报是否已生成.',
        ];
    }
}
